package asteroids.model.programs.Statement;

import asteroids.model.programs.Program;
import asteroids.model.programs.Expression.Expression;
import asteroids.model.programs.Expression.IBooleanExpression;

/**
* 
* @version 0.3
* @author  Tandan Sunil, Van Deun Luca
*
*/
public class IfThenElseLiteral extends LargeStatement {



	public IfThenElseLiteral(int line, int column, Expression condition,
			Statement then, Statement otherwise) {
		super(line, column);
		if(!(condition instanceof IBooleanExpression))
			throw new IllegalArgumentException("Condition must be of type boolean but got:"+ condition.getClass()+
					" at line:"+line +"condition type"+condition.getType().getType());
		if(then == null || otherwise == null)
			throw new IllegalArgumentException();
		this.condition = (IBooleanExpression) condition;
		this.thenStatement = then;
		this.otherwiseStatement = otherwise;
	}
	
	private Statement thenStatement;
	public Statement getThenStatement() {
		return thenStatement;
	}
	
	private IBooleanExpression condition;
	public IBooleanExpression getCondition() {
		return condition;
	}
	
	private Statement otherwiseStatement;
	public Statement getOtherwiseStatement() {
		return otherwiseStatement;
	}

	public boolean isConditionMet(){
		return condition.getBoolean();
	}
	
	@Override
	public void setExecuted(boolean executed){
	super.setExecuted(executed);
	getThenStatement().setExecuted(executed);
	getOtherwiseStatement().setExecuted(executed);
	}
	
	
	private boolean executingIf,executingElse;
	private boolean isExecutingIf(){return executingIf;}
	private boolean isExecutingElse(){return executingElse;}
	private void setExecutingIf(boolean executingIf){this.executingIf=executingIf;}
	private void setExecutingElse(boolean executingElse){this.executingElse=executingElse;}
	@Override
	public void execute(Program program) {
		if(isConditionMet() && !isExecutingIf() && !isExecutingElse()){
			getThenStatement().execute(program);
			setExecutingIf(true);
		}
		else if(isExecutingIf() && !getThenStatement().isExecuted()){
			getThenStatement().execute(program);
		}
		else if(!isConditionMet() && !isExecutingIf() && !isExecutingElse()){
			getOtherwiseStatement().execute(program);
			setExecutingElse(true);
		}
		else if(isExecutingElse() && !getOtherwiseStatement().isExecuted()){
			getOtherwiseStatement().execute(program);
		}
		
		if(getThenStatement().isExecuted() || getOtherwiseStatement().isExecuted()){
			setExecuted(true);
			setExecutingIf(false);
			setExecutingElse(false);
		
		}
		
		
		
		
	}
	

}
